/**
 * 
 */
package gpl.scotlandyard.services.utils;

import gpl.scotlandyard.beans.basics.Node;
import gpl.scotlandyard.beans.basics.Ticket;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

/** @author Norbert */
public abstract class MapLoader {

  private static final Logger LOG = Logger.getLogger(MapLoader.class);
  private static final int NB_NODES = 200;

  /** Loads nodes and links between them form given file and closes the reader.
   * @param bufr to read
   * @return map described by the file
   * @throws IOException */
  public static List<Node> loadMap(BufferedReader bufr) throws IOException {
    List<Node> map = new ArrayList<Node>(NB_NODES);

    String buffer = bufr.readLine();
    buffer = buffer == null ? "" : buffer;
    LOG.warn("first line returned null");
    StringTokenizer token = new StringTokenizer(buffer);

    int numNodes = Integer.parseInt(token.nextToken());
    LOG.debug(numNodes + " nodes to create");
    for (int i = 1; i <= numNodes; i++) {
      map.add(new Node(i));
    }

    int numLines = Integer.parseInt(token.nextToken());
    LOG.debug(numLines + " link to create");
    for (int i = 2; i <= numLines; i++) {
      buffer = bufr.readLine();
      buffer = buffer == null ? "" : buffer;
      LOG.warn("line " + i + " returned null");
      token = new StringTokenizer(buffer);
      Node n1 = map.get(Integer.parseInt(token.nextToken()) - 1);
      Node n2 = map.get(Integer.parseInt(token.nextToken()) - 1);
      Ticket t = Ticket.getTypeFor(token.nextToken());
      n1.addFullLink(n2, t);
      LOG.debug("add link : " + n1.getNumber() + "<-" + t.toString() + "->" + n2.getNumber());
    }
    bufr.close();
    LOG.info("Nodes and links loaded");
    return map;
  }

  /** Loads nodes location from the given file and closes the reader.
   * @param bufr to read
   * @param map to update
   * @throws IOException */
  public static void loadNodesLocation(BufferedReader bufr, List<Node> map) throws IOException {
    String buffer = bufr.readLine();
    buffer = buffer == null ? "" : buffer;
    LOG.warn("first line returned null");
    StringTokenizer token = new StringTokenizer(buffer);
    int numNodes = Integer.parseInt(token.nextToken());
    for (int i = 0; i < numNodes; i++) {
      buffer = bufr.readLine();
      buffer = buffer == null ? "" : buffer;
      LOG.warn("line " + i + " returned null");
      token = new StringTokenizer(buffer);
      Node n = map.get(Integer.parseInt(token.nextToken()) - 1);
      int x = Integer.parseInt(token.nextToken());
      int y = Integer.parseInt(token.nextToken());
      n.setLocation(x, y);
    }
    bufr.close();
    LOG.info("Nodes location loaded");
  }

}
